import type {
  ListOption,
  NodeInfo
} from "@/views/domain/kubeHud/api/k8s/types";

import { useK8SApi } from "@/views/domain/kubeHud/api/k8s/k8s";
import { SourceMan } from "../providers/sourceCtl";
import type { Ref } from "vue";
import type { K8sNode } from "@/views/domain/kubeHud/api/k8s/node";
const { nodeRepo } = useK8SApi();

class NodeProvider extends SourceMan<NodeInfo> {
  get nodeApi(): K8sNode {
    return nodeRepo;
  }

  isNodeReady = (node: NodeInfo): boolean => {
    return node.status.conditions.some(
      c => c.type === "Ready" && c.status === "True"
    );
  };

  get nodeList(): Ref<NodeInfo[]> {
    return this.srcList;
  }

  // 获取节点列表
  getNodes = async (req?: ListOption) => {
    const res = await nodeRepo.getNodeList({
      ...(req || this.searchQuery),
      continue: this.continue,
      limit: this.pager.limit.value
    });
    if (res.items) {
      this.continue = res.continue;
      this.srcList.value = res.items;
      this.pager.total.value = res.remainingItemCount ?? res.items.length;
    }
  };

  // 获取节点详情
  getNodeDetails = async (name: string) => {
    const res = await nodeRepo.getNodeDetail({ name });
    if (res.ok) {
    }
  };

  // 更新节点
  updateNode = async (node?: NodeInfo) => {
    const res = await nodeRepo.updateNode(node);
    if (res.ok) {
      this.refreshNodeList();
    }
  };

  // delete
  deleteNode = async (name: string) => {
    const res = await nodeRepo.deleteNode(name);
    if (res.ok) {
      this.refreshNodeList();
    }
  };

  refreshNodeList = async () => {
    this.continue = undefined;
    await this.getNodes({});
  };
}

export default new NodeProvider();
